﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jw.Models;
using Jw.Web.Areas.Senv.Common;
using System.Web.Http;
using Jw.Core;
using Newtonsoft.Json.Linq;
using Jw.Utils;
using System.Dynamic;
using Jw.Web.App_Start;

namespace Jw.Web.Areas.Senv.Controllers
{
    public class GssgtzController : BaseController
    {
        //工伤事故台账
        // GET: /Senv/Gssgtz/
        public ActionResult Index()
        {
            var codeService = new sys_codeService();
            var model = new
            {
                idField = "Gssgtz_BillNo", //主键
                urls = SenvHelper.GetIndexUrls("Gssgtz"),
                resx = SenvHelper.GetIndexResx("工伤事故台账"),
                dataSource = new
                {
                    yearItems = codeService.GetYearItems(),
                    monthItems = codeService.GetMonthItems()
                },
                form = new
                {
                    Gssgtz_Rymc = "", //人员名称
                    Gssgtz_Sgmc = "",//事故名称
                    Gssgtz_Fsrq = "",//事故发生日期
                }
            };
            return View(model);
        }
        [MvcMenuFilter(false)]
        public ActionResult Edit(string id = "")
        {
            var data = new GssgtzApiController().GetEditMaster(id);
            var codeService = new sys_codeService();

            var model = new
            {
                form = data.form,
                scrollKeys = data.scrollKeys,
                urls = SenvHelper.GetEditUrls("Gssgtz"),
                resx = SenvHelper.GetEditResx("工伤事故台账"),
                dataSource = new
                {
                    SexItems = codeService.GetTextListByType("Sex"),//性别
                    AccidentTypeItems = codeService.GetTextListByType("AccidentType"), //事故类别
                    InjuryItems = codeService.GetTextListByType("Injury")//伤害程度
                },
                defaultForm = new s_Gssgtz().Extend(new
                {
                    Gssgtz_BillNo = id
                }),
                defaultRow = new
                {
                },
                setting = new
                {
                    postFormKeys = new string[] { "Gssgtz_BillNo" },
                }
            };
            return View(model);
        }

        //工伤事故台账-月报
        public ActionResult TjcxMonthly()
        {
            var model = new
            {
                dataSource = new
                {

                },
                form = new
                {
                    sYear = DateTime.Now.Year, //单位名称
                    sMonth = DateTime.Now.Month  //发生日期
                },
                urls = new
                {
                    query = "/api/senv/gssgtz/GetTjcxMonthly/"
                }
            };
            return View(model);
        }
    }
    //api
    public class GssgtzApiController : ApiController
    {
        public string GetNewBillNo()
        {
            return new s_GssgtzService().GetNewKey("Gssgtz_BillNo", "dateplus");
        }
        public dynamic Get(RequestWrapper query)
        {
            query.LoadSettingXmlString(@"
            <settings defaultOrderBy='Gssgtz_BillNo DESC'>
            <select>*</select>
                <from>s_Gssgtz</from>
                    <where defaultForAll='true' defaultCp='equal' defaultIgnoreEmpty='true' >
                        <field name='Gssgtz_BillNo'     cp='like'></field>
                        <field name='Gssgtz_Fsrq' cp='daterange'></field>
                    </where>
            </settings>");
            var service = new s_GssgtzService();
            var pQuery = query.ToParamQuery();
            var result = service.GetDynamicListWithPaging(pQuery);

            return result;
        }

        public dynamic GetEditMaster(string id)
        {
            s_Gssgtz obj = new s_GssgtzService().GetModel(ParamQuery.Instance().AndWhere("Gssgtz_BillNo", id));
            return new
            {
                form = obj,
                scrollKeys = new s_GssgtzService().ScrollKeys("Gssgtz_BillNo", id.ToString())
            };
        }

        public void Edit(dynamic data)
        {
            var formWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>{0}</table>
                <where><field name='Gssgtz_BillNo' cp='equal'></field></where>
            </settings>", typeof(s_Gssgtz).Name);



            var result = new s_GssgtzService().Edit(formWrapper, null, data);
        }

        /// <summary>
        /// 删除主表（删除主表前是删除明细)
        /// </summary>
        /// <param name="id"></param>
        public void Delete(string id)
        {
            var result = new s_GssgtzService().Delete(ParamDelete.Instance().AndWhere("Gssgtz_BillNo", id));
            SenvHelper.ThrowHttpExceptionWhen(result <= 0, "单据删除失败[Gssgtz_BillNo={0}]，请重试或联系管理员！", id);
        }

        //审核
        [System.Web.Http.HttpPost]
        public void Audit(string id, JObject data)
        {
            var status = data["status"].ToString();
            var comment = data["comment"].ToString();
            var result = new SenvService().Audit(typeof(s_Gssgtz).Name, "Gssgtz_BillNo", id, status, comment);
            SenvHelper.ThrowHttpExceptionWhen(result < 0, "单据审核失败[Gssgtz_BillNo={0}]，请重试或联系管理员！", id);
        }

        /// <summary>
        /// 工伤事故月报(动态汇总部门数据)
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public dynamic GetTjcxMonthly(RequestWrapper query)
        {
            string sTitle = "";
            var initResult = new List<dynamic>();
            string order = query["order"] ?? string.Empty;
            int page = ZConvert.To<int>(query["page"], 1);
            int rows = ZConvert.To<int>(query["rows"], 0);
            //获取参数值
            string sYear = ZConvert.To<string>(query["sYear"], DateTime.Now.Year.ToString());
            string sMonth = ZConvert.To<string>(query["sMonth"], DateTime.Now.Month.ToString().PadLeft(2, '0'));

            string sRq = string.Format("{0}-{1}", sYear, sMonth.PadLeft(2, '0'));
            //查询发生日期
            string sqlSource = string.Format(@"select Gssgtz_Sglb,Gssgtz_Bmmc,Gssgtz_Shcd from s_Gssgtz where convert(varchar(7),Gssgtz_Fsrq,120) ='{0}'", sRq);
            //1、首先获取部门列表
            string sDwSql = string.Format(@"select distinct Gssgtz_Bmmc from ({0}) as t ", sqlSource);
            //2、获取伤害程度列表
            string sShcdSql = string.Format(@"select distinct Gssgtz_Shcd from ({0}) as t", sqlSource);

            using (var db = Db.Context("Pacm"))
            {
                //部门
                var returnDwList = db.Sql(sDwSql).QueryMany<dynamic>();
                //伤害程度
                var returnShcdList = db.Sql(sShcdSql).QueryMany<dynamic>();

                string sDynamicColumn = "";
                for (int i = 0; i < returnDwList.Count; i++)
                {
                    string sDwmc = returnDwList[i].Gssgtz_Bmmc;
                    for (int j = 0; j < returnShcdList.Count; j++)
                    {
                        string sShcd = returnShcdList[j].Gssgtz_Shcd;
                        //开始组合列，列名= 部门_伤害程度
                        sDynamicColumn += string.Format(" , isnull(sum(case when isnull(Gssgtz_Bmmc,'') = '{0}' and gssgtz_shcd = '{1}' then 1  end),0)  as UnitName{0}_{1}", sDwmc, sShcd);
                    }
                }
                //取列名
                sTitle = GetGssgtzMonthlyTitle(returnDwList, returnShcdList);
                //组合最终SQL语句(第一个语句有逗号)
                string sql = string.Format(@" select Gssgtz_Sglb {0} from ({1}) as tt group by Gssgtz_Sglb", sDynamicColumn, sqlSource);

                initResult = db.Sql(sql).QueryMany<dynamic>();
            }
            dynamic rtnData = new ExpandoObject();
            rtnData.Title = sTitle;
            rtnData.rows = initResult.Skip((page - 1) * rows).Take(rows); //分页
            rtnData.total = initResult.Count;
            return rtnData;
        }

        private string GetGssgtzMonthlyTitle(dynamic returnDwList, dynamic returnShcdList)
        {
            string sTitle = "";
            string sField = "";
            string TitleModel = @"{{""title"":""{0}"",""colspan"":{1}}},";
            string FiledModel = @"
                {{""field"":""UnitName{0}_{1}"",""title"":""{1}"",""width"":60,""align"":""center""}},";

            for (int i = 0; i < returnDwList.Count; i++)
            {
                string sDwmc = returnDwList[i].Gssgtz_Bmmc;
                //表头合并列
                sTitle += string.Format(TitleModel, sDwmc, returnShcdList.Count);
                for (int j = 0; j < returnShcdList.Count; j++)
                {
                    //字段列
                    string sShcd = returnShcdList[j].Gssgtz_Shcd;
                    sField += string.Format(FiledModel, sDwmc, sShcd);
                }
            }
            sTitle = sTitle.Remove(sTitle.LastIndexOf(","), 1);
            //去掉最后一个逗号
            sField = sField.Remove(sField.LastIndexOf(","), 1);
            string sGridColumns = string.Format(@"
            [
                [
                {{""field"":""Gssgtz_Sglb"",""title"":""事故类别"",""width"":150,""align"":""left"",""rowspan"":2}},
                {0}
                ],
                [
                {1}
                ]   
            ]", sTitle, sField);
            return sGridColumns;
        }

    }

}
